define([
	"static/app/tips",
	"UtilDir/util",
	"UtilDir/tool",
	"UtilDir/org/selectOrg",
	"UtilDir/searchBlock",
	"UtilDir/loading",
	"UtilDir/slidebar",
	"Echarts",
	"http://api.tianditu.gov.cn/api?v=4.0&tk=aeb17a8215786a5dd17f5f9c92bebc0c",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
],function(tips, Util, Tool, SelectOrg, SearchBlock, Loading, Slidebar, Echarts){

	var getBoundaryController = function(){
		return getServer() + "/boundary";
	};
	var getAnalysisMapController = function(){
		return getServer() + "/fw/AnalysisMapController";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
		initMap();
		initSearchBlock();
		queryBtnBind();

	};

	var initSearchBlock = function(){
		SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){

		$("#closeBtn").click(function () {
			$("#statisticDiv").css("display", "none");
		});

		$("#btnSearch").click(function () {
			queryData();
		});
		/*$("#btnDistrictSearch").click(function () {
			var slidebar = Slidebar({
				id : "statisticDiv",
				cache: false,
				close: true,
				afterLoad: function () {
					console.log("afterLoad");
					surveySpotsStatistic();
				}
			});
		});*/
	};

	var queryData = function () {
		clearPolygons();
		loading.show();
		$.ajax({
			url: getAnalysisMapController() + "/queryAnalysisMap",
			type: "GET",
			success: function (data) {
				console.log(data);
				if (data && data.length) {
					area2obj = {};
					for (var i = 0; i < data.length; i++) {
						var obj = data[i];
						var province = obj.province, city = obj.city, area = obj.area;
						task_thresh[province + city + area] = false;
						area2obj[province + city + area] = obj;
						querySingleAreaBoundary(obj, province, city, area);
					}
				} else {
					loading.close();
					Util.alert("查询无数据!");
				}
			}
		});
	};
	var querySingleAreaBoundary = function (obj, provinceName, cityName, areaName) {
		if (provinceName == null ||  cityName == null || areaName == null) return;
		var formData = {province: provinceName, city: cityName, area: areaName};
		$.ajax({
			url: getBoundaryController() + "/getSingleAreaBoundary",
			type: "POST",
			data: formData,
			success: function (data) {
				//console.log(provinceName, cityName, areaName, data);
				if (!data[areaName]) {
					console.log(provinceName, cityName, areaName, "无边界数据");
				} else {
					console.log(obj.count);
					var color = getColor(obj.count);
					var coords = data[areaName], geometries = coords.split("|");
					for (let i = 0; i < geometries.length; i++) {
						var geometry = geometries[i], subGeometries = geometry.split("#"), subGeometry_points = [];
						for (var j = 0; j < subGeometries.length; j++) {
							var lonlats = subGeometries[j].split(";"), lonlat, lon = 0, lat = 0, points = [];
							for (var k = 0;k < lonlats.length;k++) {
								lonlat = lonlats[k].split(",");
								lon = parseFloat(lonlat[0]); lat = parseFloat(lonlat[1]);
								points.push(new T.LngLat(lon, lat));
								global_points.push(new T.LngLat(lon, lat));
							}
							subGeometry_points.push(points);
						}
						var areaPolygon = new T.Polygon(subGeometry_points, {
							color: obj.pioneerTaskType != "2" ? color : "#999999",
							weight: 1,
							opacity: 0.7,
							fillColor: color,
							fillOpacity: 0.7,
							data: {district: provinceName + ", " + cityName + ", " + areaName, obj: obj}
						});
						tdMap.addOverLay(areaPolygon);
						areaPolygon.addEventListener("mouseover", function (object) {
							console.log(object);
							var target = object.target, lnglat = object.lnglat, data = target.options.data;
							var district = data.district, obj = data.obj, num = obj.count, mj = obj.sum;
							var divContent =
								"<div style='height: 80px;'>" +
								"<div style='height: 80px;'>" +
								"<div style='width: 350px;height: 25px;font-family: Source Han Sans CN;font-size: 16px;font-weight: normal;font-stretch: normal;line-height: 27px;letter-spacing: 0px;color: #0080ff;cursor: pointer;' onclick=_clickArea('" + obj.province + "','" + obj.city + "','" + obj.area + "');>" + district + "</div>" +

								"<div style='position: absolute;top: 40px;'>" +
								"<img src='/static/app/fwsjcj/xcNationMapStatistic/images/jsc_infowindow_point.png' width='12px' height='12px' style='position: absolute;top: 7px;'/>" +
								"<span style='position: absolute;left: 18px;width: 70px;height: 25px;font-family: Source Han Sans CN;font-size: 14px;font-weight: normal;font-stretch: normal;line-height: 24px;letter-spacing: 0px;color: #666666;'>提交的面积</span>" +
								"<span style='position: absolute;left: 240px;width: 200px;height: 25px;font-family: Source Han Sans CN;font-size: 14px;font-weight: normal;font-stretch: normal;line-height: 24px;letter-spacing: 0px;color: #333333;'>" + mj + "</span>" +
								"</div>" +

								"<div style='position: absolute;top: 68px;'>" +
								"<img src='/static/app/fwsjcj/xcNationMapStatistic/images/jsc_infowindow_point.png' width='12px' height='12px' style='position: absolute;top: 7px;'/>" +
								"<span style='position: absolute;left: 18px;width: 200px;height: 25px;font-family: Source Han Sans CN;font-size: 14px;font-weight: normal;font-stretch: normal;line-height: 24px;letter-spacing: 0px;color: #666666;'>房屋个数</span>" +
								"<span style='position: absolute;left: 240px;width: 16px;height: 25px;font-family: Source Han Sans CN;font-size: 14px;font-weight: normal;font-stretch: normal;line-height: 24px;letter-spacing: 0px;color: #333333;'>" + (num ? num : "-") + "</span>" +
								"</div>" +

								"</div>" +
								"</div>";
							global_infoWin.setContent(divContent);
							tdMap.openInfoWindow(global_infoWin, lnglat);
							$(".tdt-infowindow-content").css("width", "350px");
						});
						areaPolygon.addEventListener("click", function (object) {
							console.log(object);
							var target = object.target, data = target.options.data, obj = data.obj;
							_clickArea(obj.province, obj.city, obj.area);
						});
						global_polygons.push(areaPolygon);
					}
				}

				task_thresh[provinceName + cityName + areaName] = true;
				if (taskIsFinish(task_thresh)) {
					tdMap.setViewport(global_points);
					loading.close();
					global_points = [];
					task_thresh = {};
				}
			}
		});
	};
	window._clickArea = function (province, city, area) {
		console.log(province, city, area);
		var slidebar = Slidebar({
			id : "statisticDiv",
			cache: false,
			close: true,
			width: 500,
			afterLoad: function () {
				console.log("afterLoad");
				//queryConcurrentInfo(province, city, area);
			},
			afterOpen: function () {
				console.log("afterOpen", area2obj);
				_createSlidebarGrid(area2obj[province + city + area]);
			},
			afterClose: function () {
				console.log("afterClose");
				//$("#SlidebarMain").html("无可视分布图!");
				$("#SlidebarMain").html("");
				var tempDom = $("#SlidebarNoData").clone().show();
				$("#SlidebarMain").append(tempDom);
			}
		});
	};
	var queryConcurrentInfo = function (province, city, area) {
		loading.show();
		$.ajax({
			url: getHddcQueryController() + "/queryConcurrentInfo?province=" + province + "&city=" + city + "&area=" + area,
			type: "GET",
			success: function (result) {
				console.log(result);
				_createSlidebarGrid(area, result.data);
				loading.close();
			}
		});
	};

	var g_count_type = ["砖混结构", "多层钢筋混凝土", "高层结构", "工业厂房结构", "空旷结构", "土木结构", "木结构", "石结构", "其它"];
	var _createSlidebarGrid = function (data) {
		$("#SlidebarMain").html("");
		$("#SlidebarMain2").html("");
		var det = 48;
		if (data) {
			for (var i = 1; i <= 9; i++) {

				//面积
				var sumI = data["sum" + i];
				var _tempDom = $("#SlidebarArea2Num").clone();
				_tempDom.css("top", ((i - 1) * det) + "px").show();
				var spans = _tempDom.find('span');
				$(spans[0]).html(g_count_type[i - 1]);
				$(spans[1]).html(sumI ? sumI : 0);
				$("#SlidebarMain").append(_tempDom);

				//数量
				var countI = data["count" + i];
				var _tempDom = $("#SlidebarArea2Num").clone();
				_tempDom.css("top", ((i - 1) * det) + "px").show();
				var spans = _tempDom.find('span');
				$(spans[0]).html(g_count_type[i - 1]);
				$(spans[1]).html(countI ? countI : 0);
				$("#SlidebarMain2").append(_tempDom);
			}

		} else {

		}
	};
	var createSlidebarGrid = function (data) {
		$("#SlidebarGrid").datagrid({
			data: data,
			fitColumns: true,
			autoRowHeight: false,
			nowrap: false,
			idField: 'id',
			columns:[[
				//{field:"ck", checkbox: true},
				{
					field:'name',
					title:'活断层名称',
					width:'59%',
					align:'center',

				},
				{
					field:'attachPath',
					title:'活断层分布图',
					width:'45%',
					align:'center',
					formatter: function (value, rowData, rowIndex) {
						return "<a>" + value + "</a>";
					}
				},
			]],
			onBeforeLoad: function () {

			},
			onLoadSuccess: function () {

			},
			pagination: false,
			pageSize: 1000,
			pageList: [ 1000],
		});
	};
	var getColor = function (count) {
		var _count = count ? "1" : "0";
		return __rank_color[_count];
	};

	var clearPolygons = function (){
		tdMap.closeInfoWindow();
		for (let i = 0; i < global_polygons.length; i++) {
			tdMap.removeOverLay(global_polygons[i]);
		}
		global_polygons = [];
	};
	var taskIsFinish = function (obj) {
		for (var _key in obj) if (!obj[_key]) return false;
		return true;
	};


	var areaCount = 306, task_thresh = {};
	var level2color = {"未推送县": "#61A0A8", "已推送县": "#2F4554"}
	var leader_echarts_option = {
		/*title: {
			text: '',
			x: 'center'
		},*/
		color: ['#0000FF'],
		legend: {
			//data: ['计划共享' + areaCount + '县', '已推送xxx县', "合计条数"]
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {            // 坐标轴指示器，坐标轴触发有效
				type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
			}
		},
		grid: {
			left: '3%',
			right: '4%',
			bottom: '3%',
			containLabel: true
		},

		series: [
			{
				name: '计划共享' + areaCount + '县',
				type: 'pie',
				radius: '70%',
				data: [],
				itemStyle: {
					normal: {
						color: function(params) {
							return level2color[params.name]
						}
					}
				},
				label: {
					normal: {
						show: true,
						formatter: '{b}: {c}({d}%)'
					}
				},
			},
			{
				name: '已推送xxx县',
				type: 'pie',
				data: [],
				itemStyle: {
					normal: {
						color: function(params) {
							return level2color["已推送县"]
						}
					}
				},
			},
			{
				name: '合计条数',
				type: 'pie',
				data: []
			}
		]
	};
	var surveySpotsStatistic = function() {
		loading.show();
		var queryType = $("input[name=queryType]").filter(":checked").val();
		$.ajax({
			url: getHddcQueryController() + "/queryConcurrentInfo" ,
			type: "GET",
			success: function (data) {
				console.log(data);
				if (data) {
					var divisionNum = data.divisionNum ||　0, countNum = data.countNum || 0;
					/*leader_echarts_option.legend.data[1] = '已推送' + divisionNum + '县';
					leader_echarts_option.legend.data[2] = '合计条数:' + countNum;
					leader_echarts_option.series[0].data = [{name: "未推送县", value: (areaCount - parseInt(divisionNum))}, {name: "已推送县", value: divisionNum}];
					leader_echarts_option.series[1].name = '已推送' + divisionNum + '县';
					leader_echarts_option.series[2].name = '合计条数:' + countNum;*/

					leader_echarts_option.series[0].data = [{name: "未推送县", value: (areaCount - parseInt(divisionNum))}, {name: "已推送县", value: divisionNum}];
					$("#yts").html(divisionNum);
					$("#hjts").html(countNum);

					var dom = $("#fx-surveySpots-statistic").get(0);
					var myChart = Echarts.init(dom);

					if (leader_echarts_option && typeof leader_echarts_option === "object") {
						myChart.setOption(leader_echarts_option, true);
					}
				}
				loading.close();
			}
		});


	};




	var global_polygons = [], polygonTool, tdMap;
	var rank_color = {"轻微": "#00FF00", "一般": "#F6C568", "重点": "#FF0000"}, _rank_color = {"#00FF00": "轻微", "#F6C568": "一般", "#FF0000": "重点"};
	var __rank_color = {"0": "#FFFFFF", "1": "#FF0000", "2": "#999999"};
	var global_points = [], area2obj = {};
	var global_infoWin = new T.InfoWindow("", {minWidth: 100, maxWidth: 500, offset: new T.Point(-24, 0), autoPan: true}), loading = Loading({text : "正在查询数据..."});
	var initMap = function() {
		var mapH = document.body.clientHeight - $(".pd-search-container").height() - 10;
		$("#yhHiddenLevelMap").height(mapH);

		var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
			projection: 'EPSG:4326',
			minZoom: 4,
			layers: [vec_layer, cva_layer]
		};
		tdMap = new T.Map('yhHiddenLevelMap', config); var zoom = 4;
		tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);

		var control=new T.Control.Zoom();
		tdMap.addControl(control);

		//创建比例尺控件对象
		var scale = new T.Control.Scale();
		tdMap.addControl(scale);

	};



	return {
		init:init
	};
});
